import api from '../api/index';
import config from '../config';
import wallet from '@caomei/wallet';

function buyItem(itemKey, num, vip) {
    api.createOrder(itemKey, num, vip, config.productType).then((res) => {
        const param = {
            appId: config.appId,
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign
        };
        pay(param);
    });
}

function pay(param) {
    if (wallet.isSupportedPayType('wxpay')) {
        wallet.wxpay.payIt(param)
        .then(res => { alert('支付成功'); })
        .catch(res => {
            if (res.resultCode === wallet.wxpay.CANCEL) {
                alert('取消了支付');
            } else {
                alert('支付失败');
            }
        });
    } else {
        console.error(wallet.toString() + '不支持wxpay!'); // 当前平台为web, 环境客户端为alipay, 支持的支付类型为alipay。不支持wxpay!
    // TODO 甩锅给服务端
    }
}

export {
    buyItem,
    pay
};
